import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:path/path.dart';

void pullSmartlingFlutter([bool isInitialize = false]) {
  // 检查是否存在 smartling_flutter 代码
  final cacheDirectory = getCacheDirectory();
  final smartlingFlutterDirectory = getSmartlingDirectory();
  if (!smartlingFlutterDirectory.existsSync()) {
    // 如果没有，clone 到本地
    // git clone git@bitbucket.org:gatebackend/smartling_flutter.git
    if (isInitialize) {
      print('初始化: git clone git@bitbucket.org:gatebackend/smartling_flutter.git ${cacheDirectory.path}');
    }
    final result = Process.runSync(
      'git',
      ['clone', 'git@bitbucket.org:gatebackend/smartling_flutter.git'],
      workingDirectory: cacheDirectory.path,
    );
    if (result.exitCode != 0) {
      throw Exception('git clone failed: ${result.stderr}');
    }
  } else {
    if (isInitialize) {
      Future(() async {
        // 撤销所有变更
        await Process.run(
          'git',
          ['reset', '--hard', 'HEAD'],
          workingDirectory: smartlingFlutterDirectory.path,
        );
        // 同步最新代码
        await Process.run(
          'git',
          ['pull'],
          workingDirectory: smartlingFlutterDirectory.path,
        );
      });
    } else {
      // 撤销所有变更
      Process.runSync(
        'git',
        ['reset', '--hard', 'HEAD'],
        workingDirectory: smartlingFlutterDirectory.path,
      );
      // 同步最新代码
      Process.runSync(
        'git',
        ['pull'],
        workingDirectory: smartlingFlutterDirectory.path,
      );
    }
  }
}

/// 获取与项目关联的 smartling arb 文件列表
List<String> getAssociatedSmartlingArbs() {
  // 从当前项目目录中的配置文件中获取关联的 smartling arb 文件列表
  final configFile = getIntlViewConfigFile();
  if (configFile.existsSync()) {
    final config = configFile.readAsStringSync();
    final json = jsonDecode(config);
    final arbs = json['associated_smartling_arbs'] as List?;
    if (arbs != null) {
      return arbs.map((e) => e.toString()).toList();
    }
  }
  return [];
}

/// 设置与项目关联的 smartling arb 文件列表
void setAssociatedSmartlingArbs(List<String> arbs) {
  final configFile = getIntlViewConfigFile();
  final config = configFile.existsSync() ? jsonDecode(configFile.readAsStringSync()) : {};
  config['associated_smartling_arbs'] = arbs;
  configFile.writeAsStringSync(JsonEncoder.withIndent('  ').convert(config));
}

String? getSubmitTargetSmartlingArb() {
  final configFile = getIntlViewConfigFile();
  if (configFile.existsSync()) {
    final config = configFile.readAsStringSync();
    final json = jsonDecode(config);
    return json['submit_target_smartling_arb'] as String?;
  }
  return null;
}

void setSubmitTargetSmartlingArb(String? arb) {
  final configFile = getIntlViewConfigFile();
  final config = configFile.existsSync() ? jsonDecode(configFile.readAsStringSync()) : {};
  config['submit_target_smartling_arb'] = arb;
  configFile.writeAsStringSync(JsonEncoder.withIndent('  ').convert(config));
}

Directory getCacheDirectory() {
  final list = split(Directory.current.path);
  final path = joinAll(list.sublist(0, 3) + ['.ci_gate_cli']);
  final directory = Directory(path);
  if (!directory.existsSync()) {
    directory.createSync(recursive: true);
  }
  return directory;
}

Directory getSmartlingDirectory() {
  final cacheDirectory = getCacheDirectory();
  return Directory(join(cacheDirectory.path, 'smartling_flutter'));
}

File getIntlViewConfigFile() {
  final md5String = md5.convert(utf8.encode(Directory.current.path)).toString();
  return File(join(getCacheDirectory().path, 'intl_view_config_$md5String.json'));
}
